package com.itheima.job;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.RecommendMovement;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Set;

@Component
public class MyJob {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    MongoTemplate mongoTemplate;

    /*
        从redis中获取数据,同步到mongo的推荐动态表中
     */
    @Scheduled(cron = "0 0/1 * * * ?")//每分钟
    public void syncRecommentMovement(){
        //1.获取redis中推荐 (模糊搜索),返回集合
        Set<String> keys = stringRedisTemplate.keys("QUANZI_PUBLISH_RECOMMEND_*");

        //2.遍历集合,获取每个用户的id
        if (CollUtil.isNotEmpty(keys)) {
            for (String key : keys) {
                //3.通过用户的key获取推荐的列表(pid)
                String pidStr = stringRedisTemplate.opsForValue().get(key);

                //3.1 获取用户的id
                String userId = key.replace("QUANZI_PUBLISH_RECOMMEND_", "");

                //3.2 删除redis中数据和推荐的数据
                stringRedisTemplate.delete(key);
                mongoTemplate.remove(Query.query(Criteria.where("userId").is(NumberUtil.parseLong(userId))),RecommendMovement.class);

                //4.切分字符串生成pid的数组
                if (StrUtil.isNotBlank(pidStr)) {
                    String[] pidArr = pidStr.split(",");

                    //5.遍历pid数组,获取每个pid
                    for (String pid : pidArr) {
                        //6.封装RecommendMovement
                        RecommendMovement recommendMovement = new RecommendMovement();

                        recommendMovement.setCreated(System.currentTimeMillis());
                        recommendMovement.setUserId(NumberUtil.parseLong(userId));
                        recommendMovement.setPid(NumberUtil.parseLong(pid));
                        Movement movement = mongoTemplate.findOne(Query.query(Criteria.where("pid").is(NumberUtil.parseLong(pid))), Movement.class);
                        recommendMovement.setPublishId(movement.getId());
                        recommendMovement.setScore(RandomUtil.randomDouble(80,100));

                        //7.保存到表中
                        mongoTemplate.save(recommendMovement);
                    }
                }
            }
        }

        System.out.println("推荐已完成");
    }
}
